﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Services.Protocols;
using System.IO;

namespace EnCor.Hosting.WSHosting
{
    public class RequestHandlerFactory : MarshalByRefObject, IHttpHandlerFactory
    {
        private WebServiceMapCollection _Mapper;
        public RequestHandlerFactory(WebServiceMapCollection mapper)
        {
            _Mapper = mapper;
        }

        //private Type GetWebService(HttpRequest request)
        //{
        //    string SoapAction = request.Headers["SOAPAction"];
        //    if (SoapAction == null)
        //    {

        //        if ( dir == null )
        //        {

        //        }
        //        SoapAction = .Remove(0,1);//.QueryString["servicename"];
        //    }
        //    return _Mapper.GetWebServiceType(SoapAction);
        //    //if (request.Headers["SOAPAction"] == @"http://tempuri.org/service1/HelloWorld" || request.Url.AbsoluteUri.StartsWith("http://localhost:1040/Service1.asmx")) { return typeof(WebService1.Service1); } return null;
        //}

        #region IHttpHandlerFactory Members
        public void ReleaseHandler(IHttpHandler handler)
        {
            var wshf = new System.Web.Services.Protocols.WebServiceHandlerFactory();
            wshf.ReleaseHandler(handler);
        }

        public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
        {
            string SoapAction = context.Request.Headers["SOAPAction"];
            Type webServiceType = null;
            if (SoapAction != null &&
                (webServiceType = _Mapper.GetWebServiceType(SoapAction)) != null)
            {
                return BuildWebServiceHandler(webServiceType, context);
            }
            string dir = Path.GetDirectoryName(context.Request.FilePath);
            if (dir != null &&
                (webServiceType = _Mapper.GetWebServiceType(dir.Remove(0, 1))) != null)
            {
                return BuildWebServiceHandler(webServiceType, context);
            }

            return new ServiceIndexHttpHandler(_Mapper);
        }
        #endregion

        private IHttpHandler BuildWebServiceHandler(Type webServiceType, HttpContext context)
        {
            var wshf = new System.Web.Services.Protocols.WebServiceHandlerFactory();
            var coreGetHandler = typeof(WebServiceHandlerFactory).GetMethod("CoreGetHandler", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            var httpHandler = (IHttpHandler)coreGetHandler.Invoke(wshf, new object[] { webServiceType, context, context.Request, context.Response });
            return httpHandler;
        }
    }
}
